﻿using FySystem.Data.OrmA.Attributes;
using FySystem.Data.OrmA.Ext;
using FySystem.Data.OrmA.Reflection;
using System;
using System.Collections.Generic;
using System.Text;

namespace FySystem.Data.OrmA.Formatter
{
    class SqlFormatter : ISqlFormatter
    {
        string ISqlFormatter.ParameterMark { get { return "@"; } }

        string[] ISqlFormatter.KeywordsMark { get; } = new string[] { "[", "]" };

        DbTypes ISqlFormatter.DbType { get; } = DbTypes.Sqlserver;

        string ISqlFormatter.FormatFields(string value)
        {
            return value;
        }

        string ISqlFormatter.GetMidPKSQL(FyPrimaryKeyAttribute fyPrimaryKey)
        {
            try
            {
                if (fyPrimaryKey.PrimaryKeyType == PrimaryKeyTypes.AutoIncremental)
                    return $" OUTPUT INSERTED.{fyPrimaryKey.MappingColumn}";
                if (fyPrimaryKey.PrimaryKeyType == PrimaryKeyTypes.GUIDN)
                    return $" OUTPUT INSERTED.{fyPrimaryKey.MappingColumn}";
                else
                    return null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        string ISqlFormatter.GetPostPKSQL(FyPrimaryKeyAttribute fyPrimaryKey)
        {
            return null;
        }

        string ISqlFormatter.GetPrePKSQL(FyPrimaryKeyAttribute fyPrimaryKey)
        {
            return null;
        }

        string ISqlFormatter.ConvertDbJsonValue(object value)
        {
            throw new Exception("该数据库暂不支持Json格式字段~");
        }

        string ISqlFormatter.ToSingleSQL(string sql)
        {
            return sql;         //要改为TOP 1 这种方式比较麻烦，有时候涉及到递归查询就更难改，如果在外面套一层不确定会不会在性能上造成很大影响，所以直接返回sql，在后面查询取值的时候只取一条
        }

        string ISqlFormatter.ToPgQuerySQL(string sql, int pageNumber, int perPage, string orderBy)
        {
            try
            {
                long startRow = (pageNumber - 1) * perPage + 1;
                long endRow = pageNumber * perPage;
                orderBy = string.IsNullOrWhiteSpace(orderBy) ? "SELECT NULL" : orderBy;
                return $"SELECT FYT2.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY ({orderBy})) AS FY_RN,FYT1.* FROM ({sql}) FYT1) FYT2 WHERE FY_RN >= {startRow} AND FY_RN <= {endRow}";
            }
            catch (Exception)
            {
                throw;
            }
        }

        string ISqlFormatter.GenNvlSQL(string fieldName, object[] values)
        {
            try
            {
                if (values.IsNullOrEmpty())
                    throw new Exception("传入参数为空NVLSQL");

                var value = values[0];
                if (value.GetType() == typeof(string))
                    return $"ISNULL({fieldName}, '{value}')";
                else
                    return $"ISNULL({fieldName}, {value})";
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
